package com.ts.proj.json;


import com.alibaba.fastjson.JSONArray;
import com.ts.base.controller.BaseController;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.SystemMenuEntity;
import com.ts.proj.entity.SystemRoleEntity;
import com.ts.proj.service.SystemButtonService;
import com.ts.proj.service.SystemMenuService;
import com.ts.proj.service.SystemRoleService;
import com.ts.util.PageData;
import com.ts.util.RightsHelper;
import com.ts.util.TreeMenuUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@Slf4j
public class SystemRoleJson extends BaseController {

    @Autowired
    private SystemRoleService systemRoleService;

    @Autowired
    private SystemMenuService systemMenuService;

    @Autowired
    private SystemButtonService systemButtonService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 后台分页
     * @param start
     * @param length
     * @return
     */
    @RequestMapping("/role-list-json/{start}/{length}")
    public Map<String,Object> roleListJson(@PathVariable("start") Integer start, @PathVariable("length") Integer length){
        PageData pageData = new PageData();
        pageData.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        pageData.put("total", systemRoleService.count(pageData));
        pageData.put("rows", systemRoleService.findAll(pageData,start-1,length));
        return pageData;
    }

    /**
     * 分配权限
     * @param rights
     * @param id
     * @return
     */
    @RequestMapping("/role-assign/{rights}/{id}")
    public String roleInsUpd(@PathVariable("rights")Object rights,@PathVariable("id") Integer id){
        String newRights = "R"+ RightsHelper.sumRights(rights.toString().split(",")).toString();
        PageData pageData = new PageData();
        pageData.put("id", id);
        List<SystemRoleEntity> allOrOne = systemRoleService.findAll(pageData);
        if(null!=allOrOne||0!=allOrOne.size()){
            allOrOne.get(0).setRights(newRights);
            systemRoleService.saveAll(allOrOne);
        }
        log.info("aa");
        return "";
    }
    /**
     * 分配权限
     * @param rights
     * @param id
     * @return
     */
    @RequestMapping("/button-assign/{rights}/{id}")
    public String buttonInsUpd(@PathVariable("rights")Object rights,@PathVariable("id") Integer id){
        String newRights = "B"+ RightsHelper.sumRights(rights.toString().split(",")).toString();
        PageData pageData = new PageData();
        pageData.put("id",id);
        List<SystemRoleEntity> allOrOne = systemRoleService.findAll(pageData);
        if(null!=allOrOne||0!=allOrOne.size()){
            allOrOne.get(0).setBtnRights(newRights);
            systemRoleService.saveAll(allOrOne);
        }
        return "";
    }

    /**
     * 初始化权限
     * @param rights
     * @return
     */
    @RequestMapping(value = "/initMenu/{rights}" , produces = "application/json;charset=UTF-8")
    public Map<String,List<PageData>> initMenu(@PathVariable("rights") String rights){
        Map<String,List<PageData>> map = new HashMap<String, List<PageData>>();
        SystemMenuEntity systemMenuEntity = new SystemMenuEntity();
        systemMenuEntity.setId(0);
        systemMenuEntity.setParentId("0");
        List<SystemMenuEntity> allMenu = systemMenuService.findAll();
        List<PageData> result = new ArrayList<PageData>();
        result = new TreeMenuUtil().getTreeMenu(allMenu,systemMenuService);
        List<PageData> nodes = new ArrayList<PageData>();
        for(PageData tPageData : result ){
            if(tPageData.getString("PARENT_ID").equals("0")){
                int mu = Integer.valueOf(tPageData.get("MENU_ID").toString());
                PageData parentPD = new PageData();
                parentPD.put("id",mu);
                parentPD.put("pId",tPageData.getString("PARENT_ID"));
                parentPD.put("name",tPageData.getString("MENU_NAME"));
                parentPD.put("checked", RightsHelper.testRights(rights.substring(1),mu));
                nodes.add(parentPD);
                List<SystemMenuEntity> firstSubMenu = (List<SystemMenuEntity>) tPageData.get("firstSubMenu");
                for(SystemMenuEntity subPageData : firstSubMenu){
                    int smu = subPageData.getId();
                    PageData firstPD = new PageData();
                    firstPD.put("id",smu);
                    firstPD.put("pId",subPageData.getParentId());
                    firstPD.put("name",subPageData.getMenuName());
                    firstPD.put("checked", RightsHelper.testRights(rights.substring(1),smu));
                    nodes.add(firstPD);
                }
            }
        }
        map.put("nodes",nodes);
        return map;
    }



    @RequestMapping("/role-ins-upd-del/{id}")
    public String roleInsUpdDel(@PathVariable("id") String id){
        PageData pageData = this.getPageData();
        SystemRoleEntity roleEntity = systemRoleService.findById(Integer.valueOf(id));
        if(null!=pageData.get("roleName")&&!"".equals(pageData.getString("roleName"))){
            roleEntity.setRoleName(pageData.getString("roleName"));
        }
        if(null!=pageData.get("rights")&&!"".equals(pageData.getString("rights"))){
            roleEntity.setRights(pageData.getString("rights"));
        }
        if(null!=pageData.get("btnRights")&&!"".equals(pageData.getString("btnRights"))){
            roleEntity.setBtnRights(pageData.getString("btnRights"));
        }
        if(null!=pageData.get("deleteFlag")&&!"".equals(pageData.getString("deleteFlag"))){
            roleEntity.setDeleteFlag(InsUpdDelFlagConstant.DELETE_FLAG_Y);
        }

        try{
            stringRedisTemplate.delete("role");
        }catch (Exception e){

        }


        systemRoleService.save(roleEntity);
        return "";
    }


    @RequestMapping("/role-list")
    public Object adminGetRoleList(){
        List<PageData> pageDataList = new ArrayList<PageData>();
        PageData tempPa = new PageData();
        tempPa.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<SystemRoleEntity> roleEntities = systemRoleService.findAll(tempPa);
        for(SystemRoleEntity roleEntity : roleEntities){
            PageData pd = new PageData();
            pd.put("value",roleEntity.getId());
            pd.put("text",roleEntity.getRoleName());
            pageDataList.add(pd);
        }
        return JSONArray.toJSONString(pageDataList);
    }

    @RequestMapping("/role-id2name/{roleId}")
    public String adiminRoleId2RoleName(@PathVariable("roleId") Integer roleId){
        PageData pageData = new PageData();
        pageData.put("id", roleId);
        List<SystemRoleEntity> roleEntities = systemRoleService.findAll(pageData);
        if(1==roleEntities.size()){
            return roleEntities.get(0).getRoleName();
        }
        return "";
    }
}
